<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="设备编码" prop="equipmentCode">
        <el-input
          v-model="queryParams.equipmentCode"
          placeholder="请输入设备编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备名称" prop="equipmentName">
        <el-input
          v-model="queryParams.equipmentName"
          placeholder="请输入设备名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备类型" prop="equipmentTypeId">
        <el-cascader
          v-model="queryParams.equipmentTypeId"
          :options="typeTreeOptions"
          :props="{ 
            checkStrictly: true,
            value: 'id',
            label: 'label',
            children: 'children',
            emitPath: false
          }"
          clearable
          placeholder="请选择设备类型"
          style="width: 100%"
        ></el-cascader>
      </el-form-item>
      <el-form-item label="车间" prop="workshopId">
        <el-select 
          v-model="queryParams.workshopId" 
          placeholder="请选择车间" 
          clearable 
          filterable
          :loading="loadingWorkshops">
          <el-option
            v-for="item in workshopOptions"
            :key="item.workshopId"
            :label="item.workshopName"
            :value="item.workshopId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="设备状态" prop="equipmentStatus">
        <el-select v-model="queryParams.equipmentStatus" placeholder="请选择设备状态" clearable>
          <el-option label="空闲" value="0" />
          <el-option label="在用" value="1" />
          <el-option label="维修中" value="2" />
          <el-option label="报废" value="3" />
        </el-select>
      </el-form-item>
      <el-form-item label="采购日期" prop="purchaseDate">
        <el-date-picker clearable
          v-model="queryParams.purchaseDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择采购日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['sb:equipment-ledger:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['sb:equipment-ledger:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['sb:equipment-ledger:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="equipmentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="设备编码" align="center" prop="equipmentCode" />
      <el-table-column label="设备名称" align="center" prop="equipmentName" />
      <el-table-column label="设备类型" align="center" prop="equipmentTypeName" />
      <el-table-column label="车间" align="center" prop="workshopName" />
      <el-table-column label="设备状态" align="center" prop="equipmentStatus">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.equipmentStatus === '0'" type="success">空闲</el-tag>
          <el-tag v-else-if="scope.row.equipmentStatus === '1'" type="warning">在用</el-tag>
          <el-tag v-else-if="scope.row.equipmentStatus === '2'" type="danger">维修中</el-tag>
          <el-tag v-else-if="scope.row.equipmentStatus === '3'" type="info">报废</el-tag>
          <el-tag v-else type="info">未知</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="管理人" align="center" prop="responsiblePerson" />
      <el-table-column label="采购价格" align="center" prop="purchasePrice">
        <template slot-scope="scope">
          <span>{{ scope.row.purchasePrice ? parseFloat(scope.row.purchasePrice).toFixed(2) : "0.00" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="采购日期" align="center" prop="purchaseDate" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.purchaseDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleDetail(scope.row)"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['sb:equipment-ledger:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['sb:equipment-ledger:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改设备管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-divider content-position="left">基本信息</el-divider>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="设备编码" prop="equipmentCode">
              <el-input v-model="form.equipmentCode" placeholder="请输入设备编码" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备名称" prop="equipmentName">
              <el-input v-model="form.equipmentName" placeholder="请输入设备名称" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="设备类型" prop="equipmentTypeId">
              <el-cascader
                v-model="form.equipmentTypeId"
                :options="typeTreeOptions"
                :props="{ 
                  checkStrictly: true,
                  value: 'id',
                  label: 'label',
                  children: 'children',
                  emitPath: false
                }"
                clearable
                placeholder="请选择设备类型"
                style="width: 100%"
                disabled
              ></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备状态" prop="equipmentStatus">
              <el-select v-model="form.equipmentStatus" placeholder="请选择设备状态" style="width: 100%">
                <el-option label="空闲" value="0" />
                <el-option label="在用" value="1" />
                <el-option label="维修中" value="2" />
                <el-option label="报废" value="3" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="所属车间" prop="workshopId">
                <el-input
                  v-model="form.workshopName"
                  placeholder="请选择车间"
                  readonly
                  @click.native="openWorkshopSelect"
                  class="select-input"
                  suffix-icon="el-icon-arrow-down"
                />
                <!-- 车间选择弹窗 -->
                <el-dialog
                  title="选择车间"
                  :visible.sync="showWorkshopSelect"
                  width="600px"
                  append-to-body
                >
                  <el-form :inline="true" class="dialog-search-form">
                    <el-form-item label="车间名称">
                      <el-input
                        v-model="workshopSearchName"
                        placeholder="请输入车间名称"
                        clearable
                        size="small"
                        @keyup.enter.native="searchWorkshops"
                      />
                    </el-form-item>
                    <el-form-item>
                      <el-button type="primary" icon="el-icon-search" size="small" @click="searchWorkshops">搜索</el-button>
                      <el-button icon="el-icon-refresh" size="small" @click="resetWorkshopSearch">重置</el-button>
                    </el-form-item>
                  </el-form>
                  <el-table
                    :data="filteredWorkshopOptions"
                    @row-click="selectWorkshop"
                    highlight-current-row
                style="width: 100%"
                    height="350px"
                  >
                    <el-table-column type="index" label="序号" width="50" align="center" />
                    <el-table-column prop="workshop_name" label="车间名称" min-width="150" show-overflow-tooltip />
                    <el-table-column label="操作" align="center" width="80">
                      <template slot-scope="scope">
                        <el-button size="mini" type="primary" plain @click.stop="selectWorkshop(scope.row)">选择</el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </el-dialog>
            </el-form-item>
            <el-form-item label="所属生产线" prop="productionLineId">
                <el-input
                  v-model="form.productionLineName"
                  placeholder="请选择生产线"
                  readonly
                  @click.native="openProductionLineSelect"
                  class="select-input"
                  suffix-icon="el-icon-arrow-down"
                  :disabled="!form.workshopId"
                />
                <!-- 生产线选择弹窗 -->
                <el-dialog
                  title="选择生产线"
                  :visible.sync="showProductionLineSelect"
                  width="600px"
                  append-to-body
                >
                  <el-form :inline="true" class="dialog-search-form">
                    <el-form-item label="生产线名称">
                      <el-input
                        v-model="productionLineSearchName"
                        placeholder="请输入生产线名称"
                        clearable
                        size="small"
                        @keyup.enter.native="searchProductionLines"
                      />
                    </el-form-item>
                    <el-form-item>
                      <el-button type="primary" icon="el-icon-search" size="small" @click="searchProductionLines">搜索</el-button>
                      <el-button icon="el-icon-refresh" size="small" @click="resetProductionLineSearch">重置</el-button>
                    </el-form-item>
                  </el-form>
                  <el-table
                    :data="filteredProductionLineOptions"
                    @row-click="selectProductionLine"
                    highlight-current-row
                style="width: 100%"
                    height="350px"
                  >
                    <el-table-column type="index" label="序号" width="50" align="center" />
                    <el-table-column prop="production_line_name" label="生产线名称" min-width="150" show-overflow-tooltip />
                    <el-table-column label="操作" align="center" width="80">
                      <template slot-scope="scope">
                        <el-button size="mini" type="primary" plain @click.stop="selectProductionLine(scope.row)">选择</el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </el-dialog>
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">管理与维护</el-divider>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="管理人" prop="responsiblePerson">
              <el-input v-model="form.responsiblePerson" placeholder="请选择管理人" readonly>
                <el-button slot="append" icon="el-icon-user" @click="openUserSelectDialog"></el-button>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="采购日期" prop="purchaseDate">
              <el-date-picker
                v-model="form.purchaseDate"
                type="date"
                style="width: 100%"
                value-format="yyyy-MM-dd"
                placeholder="请选择采购日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="采购价格" prop="purchasePrice">
              <el-input-number v-model="form.purchasePrice" :min="0" :precision="2" :step="1000" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备图片" prop="imageUrl">
              <el-upload
                class="avatar-uploader"
                action="#"
                :show-file-list="false"
                :on-success="handleUploadSuccess"
                :before-upload="beforeUpload"
                :http-request="uploadFile">
                <img v-if="form.imageUrl" :src="form.imageUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">保 存</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 用户选择对话框 -->
    <el-dialog title="选择管理人员" :visible.sync="userSelectVisible" width="800px" append-to-body>
      <!-- 搜索区域 -->
      <el-form :model="userQueryParams" ref="userQueryForm" :inline="true">
        <el-form-item label="用户名称" prop="userName">
          <el-input
            v-model="userQueryParams.userName"
            placeholder="请输入用户名称"
            clearable
            size="small"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item label="手机号码" prop="phonenumber">
          <el-input
            v-model="userQueryParams.phonenumber"
            placeholder="请输入手机号码"
            clearable
            size="small"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="small" @click="handleUserQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="small" @click="handleUserReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 用户列表 -->
      <el-table
        v-loading="userLoading"
        :data="userList"
        @row-click="selectUser"
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column type="index" label="序号" width="50" align="center" />
        <el-table-column prop="userName" label="用户名称" min-width="100" show-overflow-tooltip />
        <el-table-column prop="nickName" label="用户昵称" min-width="100" show-overflow-tooltip />
        <el-table-column prop="phonenumber" label="手机号码" min-width="120" show-overflow-tooltip />
        <el-table-column prop="dept.deptName" label="部门" min-width="120" show-overflow-tooltip>
          <template slot-scope="scope">
            <span>{{ scope.row.dept ? scope.row.dept.deptName : '' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="80">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click.stop="selectUser(scope.row)">选择</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="userTotal > 0"
        :total="userTotal"
        :page.sync="userQueryParams.pageNum"
        :limit.sync="userQueryParams.pageSize"
        @pagination="loadUserList"
      />
    </el-dialog>
  </div>
</template>

<script>
import { listEquipment, getEquipment, delEquipment, addEquipment, updateEquipment, checkEquipmentCodeExcludeSelf } from "@/api/sb/equipmentLedger";
import { listEquipmentType, getEquipmentTypeTree } from "@/api/sb/equipmentType";
import { upload } from "@/api/common/upload";
import { listWorkshop } from "@/api/basic/factory";
import { getProductionLinesByWorkshop } from "@/api/basic/line";
import { listUser } from "@/api/system/user";

export default {
  name: "EquipmentLedger",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备台账表格数据
      equipmentList: null,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        equipmentCode: null,
        equipmentName: null,
        equipmentTypeId: null,
        equipmentStatus: null,
        location: null,
        departmentName: null,
        model: null,
        specifications: null,
        manufacturer: null,
        purchaseDate: null,
        purchasePrice: null,
        responsiblePerson: null,
        userId: null,
        workshopId: null,
        productionLineId: null,
        params: {
          beginPurchaseDate: null,
          endPurchaseDate: null,
        }
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        equipmentCode: [
          { required: true, message: "设备编码不能为空", trigger: "blur" }
        ],
        equipmentName: [
          { required: true, message: "设备名称不能为空", trigger: "blur" }
        ],
        equipmentTypeId: [
          { required: true, message: "设备类型不能为空", trigger: "change" }
        ],
        equipmentStatus: [
          { required: true, message: "设备状态不能为空", trigger: "change" }
        ],
        workshopId: [
          { required: true, message: "所属车间不能为空", trigger: "change" }
        ],
        productionLineId: [
          { required: true, message: "所属生产线不能为空", trigger: "change" }
        ],
        responsiblePerson: [
          { required: true, message: "管理人不能为空", trigger: "blur" }
        ]
      },
      // 设备类型树形选项
      typeTreeOptions: [],
      // 车间选项
      workshopOptions: [],
      // 生产线选项
      productionLineOptions: [],
      // 节流控制
      lastCallTime: {
        workshops: 0,
        productionLines: 0
      },
      THROTTLE_TIME: 500,
      // 加载状态
      loadingWorkshops: false,
      loadingProductionLines: false,
      // 用户选择相关
      userSelectVisible: false,
      userLoading: false,
      userList: [],
      userTotal: 0,
      userQueryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined
      },
      // 车间选择弹窗
      showWorkshopSelect: false,
      // 生产线选择弹窗
      showProductionLineSelect: false,
      // 车间搜索名称
      workshopSearchName: '',
      // 生产线搜索名称
      productionLineSearchName: '',
      // 过滤后的车间选项
      filteredWorkshopOptions: [],
      // 过滤后的生产线选项
      filteredProductionLineOptions: []
    };
  },
  created() {
    this.getList();
    this.getTypeOptions();
    this.loadWorkshopOptions(); // 加载车间选项
  },
  methods: {
    // 获取设备类型选项
    getTypeOptions() {
      getEquipmentTypeTree().then(response => {
        if (response.code === 200 && response.data) {
          this.typeTreeOptions = this.formatTreeData(response.data);
        } else {
          this.typeTreeOptions = [];
          console.error("获取设备类型树形列表失败:", response);
        }
      });
    },
    
    // 格式化树形数据
    formatTreeData(data) {
      return data.map(item => {
        const node = {
          id: item.id || item.typeId,
          label: item.label || item.typeName,
          typeId: item.id || item.typeId,
          typeCode: item.typeCode,
          children: item.children && item.children.length > 0 ? this.formatTreeData(item.children) : []
        };
        console.log("格式化树节点:", node);
        return node;
      });
    },
    /** 查询设备管理列表 */
    getList() {
      this.loading = true;
      console.log("查询参数:", JSON.stringify(this.queryParams));
      listEquipment(this.queryParams).then(response => {
        this.equipmentList = response.rows;
        this.total = parseInt(response.total) || 0;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        equipmentCode: '',
        equipmentName: '',
        equipmentTypeId: null,
        equipmentStatus: '0',
        workshopId: null,
        productionLineId: null,
        imageUrl: '',
        responsiblePerson: '',
        userNickName: '',
        purchaseDate: '',
        purchasePrice: 0,
        remark: ''
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      // 确保查询参数中的设备类型ID是正确的
      if (this.queryParams.equipmentTypeId) {
        console.log("查询设备类型ID:", this.queryParams.equipmentTypeId);
      }
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.equipmentTypeId = null; // 确保设备类型被重置
      this.queryParams.workshopId = null; // 确保车间被重置
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.equipmentId || item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$router.push({ path: "/sb/equipment-ledger/add" });
    },
    /** 查看详情按钮操作 */
    handleDetail(row) {
      console.log('设备详情行数据:', row);
      const equipmentId = row.equipmentId || row.id;
      if (!equipmentId) {
        this.$modal.msgError("未获取到设备ID，无法查看详情！");
        return;
      }
      console.log('使用的设备ID:', equipmentId);
      this.$router.push({ path: `/sb/equipment-ledger/detail/${equipmentId}` });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const equipmentId = row.equipmentId || row.id || this.ids[0];
      if (!equipmentId) {
        this.$modal.msgError("未获取到设备ID，无法修改！");
        return;
      }
      
      // 显示加载中
      const loading = this.$loading({
        lock: true,
        text: '加载设备数据...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      
      // 先加载车间选项
      this.loadWorkshopOptions().then(() => {
        // 获取设备数据
      getEquipment(equipmentId).then(response => {
        console.log("获取设备数据:", response.data);
        this.form = response.data;
        
        // 确保imageUrl是有效的路径
        if (this.form.imageUrl) {
          // 如果不是完整路径，添加API前缀
          if (!this.form.imageUrl.startsWith('http') && !this.form.imageUrl.startsWith('/')) {
            this.form.imageUrl = process.env.VUE_APP_BASE_API + this.form.imageUrl;
          }
          console.log("设置图片URL:", this.form.imageUrl);
        }
        
          // 设置车间名称
          if (this.form.workshopId && this.workshopOptions.length > 0) {
            const workshop = this.workshopOptions.find(item => item.workshop_id == this.form.workshopId);
            if (workshop) {
              this.form.workshopName = workshop.workshop_name;
              console.log("设置车间名称:", this.form.workshopName);
            }
          }
          
          // 如果有车间ID，加载生产线选项
          const promises = [];
          if (this.form.workshopId) {
            promises.push(this.loadProductionLineOptions().then(() => {
              // 设置生产线名称
              if (this.form.productionLineId && this.productionLineOptions.length > 0) {
                const line = this.productionLineOptions.find(item => item.production_line_id == this.form.productionLineId);
                if (line) {
                  this.form.productionLineName = line.production_line_name;
                  console.log("设置生产线名称:", this.form.productionLineName);
          }
              }
            }));
          }
          
          // 如果本地没有找到名称，尝试从后端获取
          promises.push(this.fetchWorkshopAndLineNames());
          
          // 等待所有数据加载完成后再打开弹窗
          Promise.all(promises).finally(() => {
            loading.close();
            this.open = true;
            this.title = "修改设备";
          });
        }).catch(error => {
          loading.close();
          console.error("获取设备数据失败:", error);
          this.$modal.msgError("获取设备数据失败: " + (error.message || JSON.stringify(error)));
        });
      }).catch(error => {
        loading.close();
        console.error("加载车间数据失败:", error);
        this.$modal.msgError("加载车间数据失败: " + (error.message || JSON.stringify(error)));
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 确保车间和生产线名称正确
          if (this.form.workshopId) {
            const workshop = this.workshopOptions.find(item => item.workshop_id == this.form.workshopId);
            if (workshop) {
              this.form.workshopName = workshop.workshop_name;
              console.log("提交前设置车间名称:", this.form.workshopName);
            }
              }
              
          if (this.form.productionLineId) {
            const line = this.productionLineOptions.find(item => item.production_line_id == this.form.productionLineId);
            if (line) {
              this.form.productionLineName = line.production_line_name;
              console.log("提交前设置生产线名称:", this.form.productionLineName);
              }
          }
          
          updateEquipment(this.form).then(response => {
            this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
          }).catch(err => {
            console.error("更新设备数据失败:", err);
            this.$modal.msgError("更新失败: " + (err.message || JSON.stringify(err)));
            });
        }
      });
    },
    
    // 提交设备数据
    submitEquipmentData() {
      console.log("提交数据，图片URL:", this.form.imageUrl);
      
      // 确保车间和生产线名称正确
      if (this.form.workshopId) {
        const workshop = this.workshopOptions.find(item => item.workshop_id == this.form.workshopId);
        if (workshop) {
          this.form.workshopName = workshop.workshop_name;
        }
      }
      
      if (this.form.productionLineId) {
        const line = this.productionLineOptions.find(item => item.production_line_id == this.form.productionLineId);
        if (line) {
          this.form.productionLineName = line.production_line_name;
        }
      }
      
      updateEquipment(this.form).then(response => {
        this.$modal.msgSuccess("修改成功");
        this.open = false;
        this.getList();
      }).catch(err => {
        console.error("更新设备数据失败:", err);
        this.$modal.msgError("更新失败: " + (err.message || JSON.stringify(err)));
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const equipmentIds = row.equipmentId || row.id || this.ids;
      this.$modal.confirm('是否确认删除设备管理编号为"' + equipmentIds + '"的数据项？').then(function() {
        return delEquipment(equipmentIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    // 上传前校验
    beforeUpload(file) {
      const isImage = file.type.indexOf('image/') === 0;
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isImage) {
        this.$message.error('上传文件只能是图片格式!');
        return false;
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
        return false;
      }
      return true;
    },
    // 上传成功回调
    handleUploadSuccess(res, file) {
      // 如果响应中有URL，使用服务器返回的URL
      if (res && res.url) {
        this.form.imageUrl = res.url;
      } else if (res && res.data && res.data.url) {
        this.form.imageUrl = res.data.url;
      } else {
        // 临时创建一个Object URL用于预览，但不会保存到数据库
      this.form.imageUrl = URL.createObjectURL(file.raw);
      }
    },
    // 自定义上传
    uploadFile(options) {
      // 使用XHR上传
      const xhr = new XMLHttpRequest();
      const formData = new FormData();
      formData.append('avatarfile', options.file);

      const token = this.$store.getters.token;

      xhr.open('POST', process.env.VUE_APP_BASE_API + '/ldzl-sb/sb/upload/image', true);
      xhr.setRequestHeader('Authorization', 'Bearer ' + token);

      xhr.onload = function() {
        if (xhr.status === 200) {
          try {
            const res = JSON.parse(xhr.responseText);
            console.log('图片上传响应:', res);
            let imageUrl = '';
            if (res.data && res.data.url) {
              imageUrl = res.data.url;
            } else if (res.url) {
              imageUrl = res.url;
            } else if (res.imgUrl) {
              imageUrl = res.imgUrl;
            } else if (res.data && typeof res.data === 'string') {
              imageUrl = res.data;
            } else if (res.data) {
              const possibleFields = ['url', 'imgUrl', 'imageUrl', 'path', 'filePath', 'fileName'];
              for (const field of possibleFields) {
                if (res.data[field]) {
                  imageUrl = res.data[field];
                  break;
                }
              }
            }
            if (imageUrl) {
              if (imageUrl && !imageUrl.startsWith('http') && !imageUrl.startsWith('/')) {
                imageUrl = process.env.VUE_APP_BASE_API + imageUrl;
              }
              this.form.imageUrl = imageUrl; 
              console.log('设置图片URL:', imageUrl);
              options.onSuccess(res);
            } else {
              console.error('无法从响应中获取图片URL:', res);
              options.onError(new Error('无法获取图片URL'));
            }
          } catch (e) {
            console.error('解析响应失败:', e);
            options.onError(e);
          }
        } else {
          console.error('图片上传请求失败:', xhr.status);
          options.onError(new Error('图片上传请求失败: ' + xhr.status));
        }
      }.bind(this); // 绑定this到组件实例

      xhr.onerror = function() {
        console.error('上传文件请求错误');
        options.onError(new Error('上传文件请求错误'));
      };
      xhr.send(formData);
    },
    // 加载车间选项
    loadWorkshopOptions() {
      const now = Date.now();
      if (now - this.lastCallTime.workshops < this.THROTTLE_TIME) {
        return Promise.resolve(this.workshopOptions);
      }
      this.lastCallTime.workshops = now;
      this.loadingWorkshops = true;
      
      console.log("开始加载车间选项");
      
      return listWorkshop({pageSize: 100}).then(response => {
        console.log("车间数据响应:", response);
        if (response.code === 200 && response.rows) {
          this.workshopOptions = response.rows.map(item => ({
            workshop_id: item.workshop_id || item.workshopId,
            workshop_name: item.workshop_name || item.workshopName
          }));
          console.log("加载到车间选项:", this.workshopOptions);
        } else {
          this.workshopOptions = [];
          console.error("获取车间数据失败:", response.msg || "未知错误");
        }
        this.loadingWorkshops = false;
        return this.workshopOptions;
      }).catch(error => {
        this.workshopOptions = [];
        this.loadingWorkshops = false;
        console.error("加载车间选项失败:", error);
        return Promise.reject(error);
      });
    },
    
    // 加载生产线选项
    loadProductionLineOptions() {
      const now = Date.now();
      if (now - this.lastCallTime.productionLines < this.THROTTLE_TIME || !this.form.workshopId) {
        return Promise.resolve(this.productionLineOptions);
      }
      this.lastCallTime.productionLines = now;
      this.loadingProductionLines = true;
      
      console.log("加载生产线选项，车间ID:", this.form.workshopId);
      
      // 仅当第一次加载或生产线选项为空时显示loading
      let loading = null;
      if (this.productionLineOptions.length === 0) {
        loading = this.$loading({
          lock: true,
          text: '加载生产线数据...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
      }
      
      return getProductionLinesByWorkshop(this.form.workshopId).then(response => {
        console.log("生产线数据响应:", response);
        
        if (response.code === 200) {
          if (response.data && Array.isArray(response.data) && response.data.length > 0) {
            this.productionLineOptions = response.data.map(item => ({
              production_line_id: item.production_line_id || item.lineId,
              production_line_name: item.production_line_name || item.lineName
            }));
            console.log("获取到生产线数据:", this.productionLineOptions.length, "条");
          } else if (response.rows && Array.isArray(response.rows) && response.rows.length > 0) {
          this.productionLineOptions = response.rows.map(item => ({
              production_line_id: item.production_line_id || item.lineId,
              production_line_name: item.production_line_name || item.lineName
          }));
            console.log("获取到生产线数据:", this.productionLineOptions.length, "条");
        } else {
            console.warn("未找到生产线数据");
          this.productionLineOptions = [];
        }
        } else {
          console.error("获取生产线列表失败:", response.msg);
          this.productionLineOptions = [];
        }
        
        this.loadingProductionLines = false;
        if (loading) loading.close();
        return this.productionLineOptions;
      }).catch(error => {
        console.error("获取生产线列表错误:", error);
        
        // 静默处理操作频繁的错误
        if (error.message && error.message.includes("操作过于频繁")) {
          console.log("忽略频繁操作错误");
        } else {
          // 其他错误可以考虑显示
          // this.$message.error("获取生产线失败，请重试");
        }
        
        this.productionLineOptions = [];
        this.loadingProductionLines = false;
        if (loading) loading.close();
        return Promise.reject(error);
      });
    },
    
    // 车间选择变更
    handleWorkshopChange() {
      console.log("车间选择变更:", this.form.workshopId);
      
      // 清空生产线相关数据
      this.form.productionLineId = null;
      this.form.productionLineName = '';
      this.productionLineOptions = []; // 先清空选项
      
      if (!this.form.workshopId) {
        this.form.workshopName = '';
        return;
      }
      
      // 获取车间名称
      const workshop = this.workshopOptions.find(item => item.workshop_id == this.form.workshopId);
      if (workshop) {
        this.form.workshopName = workshop.workshop_name;
        console.log("设置车间名称:", this.form.workshopName);
      }
      
      // 加载对应的生产线选项
      this.loadProductionLineOptions();
    },

    // 生产线选择变更
    handleProductionLineChange() {
      console.log("生产线选择变更:", this.form.productionLineId);
      if (this.form.productionLineId) {
        const line = this.productionLineOptions.find(item => item.production_line_id == this.form.productionLineId);
        if (line) {
          this.form.productionLineName = line.production_line_name;
          console.log("设置生产线名称:", this.form.productionLineName);
        }
      } else {
        this.form.productionLineName = '';
      }
    },
    
    // 打开用户选择对话框
    openUserSelectDialog() {
      this.userSelectVisible = true;
      this.loadUserList();
    },
    
    // 加载用户列表
    loadUserList() {
      this.userLoading = true;
      listUser(this.userQueryParams).then(response => {
        this.userList = response.rows;
        this.userTotal = parseInt(response.total) || 0;
        this.userLoading = false;
      }).catch(() => {
        this.userLoading = false;
      });
    },
    
    // 用户查询
    handleUserQuery() {
      this.userQueryParams.pageNum = 1;
      this.loadUserList();
    },
    
    // 用户重置
    handleUserReset() {
      this.resetForm("userQueryForm");
      this.handleUserQuery();
    },
    
    // 选择用户
    selectUser(row) {
      this.form.responsiblePerson = row.nickName;
      this.form.userId = row.userId;
      this.form.departmentId = row.dept ? row.dept.deptId : null;
      this.form.departmentName = row.dept ? row.dept.deptName : '';
      this.userSelectVisible = false;
    },
    // 选择车间
    selectWorkshop(row) {
      this.form.workshopId = row.workshop_id;
      this.form.workshopName = row.workshop_name;
      this.showWorkshopSelect = false;
      
      // 清空生产线相关数据
      this.form.productionLineId = null;
      this.form.productionLineName = '';
      this.productionLineOptions = []; // 先清空选项
      
      // 加载对应的生产线选项
      this.loadProductionLineOptions();
    },
    
    // 选择生产线
    selectProductionLine(row) {
      this.form.productionLineId = row.production_line_id;
      this.form.productionLineName = row.production_line_name;
      this.showProductionLineSelect = false;
    },
    // 格式化设备状态
    formatStatus(status) {
      const statusMap = {
        '0': '空闲',
        '1': '在用',
        '2': '维修中',
        '3': '报废'
      };
      return statusMap[status] || status;
    },
    // 根据ID获取车间和生产线名称
    fetchWorkshopAndLineNames() {
      if (!this.form.workshopId && !this.form.productionLineId) {
        return Promise.resolve();
      }
      
      const promises = [];
      
      // 如果有车间ID但没有车间名称，从后端获取
      if (this.form.workshopId && !this.form.workshopName) {
        // 从现有选项中查找
        const workshop = this.workshopOptions.find(item => item.workshop_id == this.form.workshopId);
        if (workshop) {
          this.form.workshopName = workshop.workshop_name;
          console.log("从本地选项中获取车间名称:", this.form.workshopName);
        } else {
          // 从后端获取
          console.log("从后端获取车间名称，ID:", this.form.workshopId);
          const p1 = listWorkshop({pageSize: 500}).then(response => {
            if (response.code === 200 && response.rows) {
              const workshop = response.rows.find(item => 
                (item.workshop_id == this.form.workshopId) || 
                (item.workshopId == this.form.workshopId)
              );
              if (workshop) {
                this.form.workshopName = workshop.workshop_name || workshop.workshopName;
                console.log("从后端获取到车间名称:", this.form.workshopName);
              }
            }
          }).catch(error => {
            console.error("获取车间名称失败:", error);
          });
          promises.push(p1);
        }
      }
      
      // 如果有生产线ID但没有生产线名称，从后端获取
      if (this.form.productionLineId && !this.form.productionLineName && this.form.workshopId) {
        // 从现有选项中查找
        const line = this.productionLineOptions.find(item => item.production_line_id == this.form.productionLineId);
        if (line) {
          this.form.productionLineName = line.production_line_name;
          console.log("从本地选项中获取生产线名称:", this.form.productionLineName);
        } else {
          // 从后端获取
          console.log("从后端获取生产线名称，ID:", this.form.productionLineId);
          const p2 = getProductionLinesByWorkshop(this.form.workshopId).then(response => {
            if (response.code === 200) {
              let lines = [];
              if (response.data && Array.isArray(response.data)) {
                lines = response.data;
              } else if (response.rows && Array.isArray(response.rows)) {
                lines = response.rows;
              }
              
              const line = lines.find(item => 
                (item.production_line_id == this.form.productionLineId) || 
                (item.lineId == this.form.productionLineId)
              );
              if (line) {
                this.form.productionLineName = line.production_line_name || line.lineName;
                console.log("从后端获取到生产线名称:", this.form.productionLineName);
              }
            }
          }).catch(error => {
            console.error("获取生产线名称失败:", error);
          });
          promises.push(p2);
        }
      }
      
      return Promise.all(promises);
    },
    // 打开车间选择弹窗
    openWorkshopSelect() {
      // 先加载车间选项
      this.loadWorkshopOptions().then(() => {
        this.workshopSearchName = ''; // 清空搜索关键词
        this.filteredWorkshopOptions = [...this.workshopOptions]; // 初始化过滤列表
        this.showWorkshopSelect = true;
      }).catch(error => {
        console.error("加载车间选项失败:", error);
        this.$message.error("加载车间选项失败，请重试");
      });
    },
    
    // 打开生产线选择弹窗
    openProductionLineSelect() {
      if (!this.form.workshopId) {
        this.$message.warning("请先选择车间");
        return;
      }
      
      // 先加载生产线选项
      this.loadProductionLineOptions().then(() => {
        this.productionLineSearchName = ''; // 清空搜索关键词
        this.filteredProductionLineOptions = [...this.productionLineOptions]; // 初始化过滤列表
        this.showProductionLineSelect = true;
      }).catch(error => {
        console.error("加载生产线选项失败:", error);
        this.$message.error("加载生产线选项失败，请重试");
      });
    },

    // 搜索车间
    searchWorkshops() {
      if (!this.workshopSearchName) {
        this.filteredWorkshopOptions = [...this.workshopOptions];
        return;
      }
      
      this.filteredWorkshopOptions = this.workshopOptions.filter(item => 
        item.workshop_name && item.workshop_name.toLowerCase().includes(this.workshopSearchName.toLowerCase())
      );
      
      if (this.filteredWorkshopOptions.length === 0) {
        this.$message.warning("未找到相关车间，请尝试其他关键词。");
      }
    },

    // 重置车间搜索
    resetWorkshopSearch() {
      this.workshopSearchName = '';
      this.filteredWorkshopOptions = [...this.workshopOptions];
    },

    // 搜索生产线
    searchProductionLines() {
      if (!this.productionLineSearchName) {
        this.filteredProductionLineOptions = [...this.productionLineOptions];
        return;
      }
      
      this.filteredProductionLineOptions = this.productionLineOptions.filter(item => 
        item.production_line_name && item.production_line_name.toLowerCase().includes(this.productionLineSearchName.toLowerCase())
      );
      
      if (this.filteredProductionLineOptions.length === 0) {
        this.$message.warning("未找到相关生产线，请尝试其他关键词。");
      }
    },

    // 重置生产线搜索
    resetProductionLineSearch() {
      this.productionLineSearchName = '';
      this.filteredProductionLineOptions = [...this.productionLineOptions];
    }
  }
};
</script>

<style scoped>
.el-form-item__description {
  font-size: 12px;
  color: #606266;
  display: block;
  margin-top: 4px;
}

/* 自定义选择框样式 */
.select-input {
  cursor: pointer;
}

.select-input /deep/ .el-input__inner {
  cursor: pointer;
  background-color: #fff;
}

.select-input /deep/ .el-input__suffix {
  color: #C0C4CC;
  font-size: 14px;
  transition: all .3s;
}

.select-input:hover /deep/ .el-input__inner {
  border-color: #409EFF;
}

.select-input:hover /deep/ .el-input__suffix {
  color: #409EFF;
}

/* 弹窗搜索表单样式 */
.dialog-search-form {
  margin-bottom: 15px;
}

.dialog-search-form .el-form-item {
  margin-bottom: 10px;
}

.dialog-search-form .el-form-item__label {
  font-weight: normal;
  color: #606266;
}

.dialog-search-form .el-input {
  width: 220px;
}

/* 上传图片样式 */
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 128px;
  height: 128px;
  line-height: 128px;
  text-align: center;
}
.avatar {
  width: 128px;
  height: 128px;
  display: block;
}
</style>
